package org.ccay.core.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.ccay.core.log.ILogger;
import org.ccay.core.log.CcayLoggerFactory;

/**
 * map帮助类
 * 
 */
public class MapUtil {

	private static final ILogger log = CcayLoggerFactory.getLogger(MapUtil.class);
	/**
	 * 对象转MAP
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> objectToMap(Object obj) {
		if(obj == null){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
	
		Method[] methods = obj.getClass().getMethods();
		for (Method method : methods) {
			try {
				if (method.getName().startsWith("get")) {
					String field = toFirstLower(method.getName().replace("get", ""));
					Object objValue = method.invoke(obj, null);
					map.put(field, objValue);
				}
			} catch (Exception e) {
				log.error(e);
			}
		}
		Class<?> superClass = obj.getClass().getSuperclass();
		while (!superClass.getName().equals("java.lang.Object")) {
			Method[] superMethods = superClass.getMethods();
			for (Method method : superMethods) {
				try {
					if (method.getName().startsWith("get")) {
						String field = toFirstLower(method.getName().replace("get", ""));
						Object objValue = method.invoke(obj, null);
						map.put(field, objValue);
					}
				} catch (Exception e) {
					log.error(e);
				}
			}
			superClass = superClass.getSuperclass();
		}
		return map;
	}
	
	private static String toFirstLower(String str) {
		if (str == null || "".equals(str)) {
			return "";
		}
		char[] chars = new char[1];  
		chars[0] = str.charAt(0);  
		String temp = new String(chars);  
		return str.replaceFirst(temp,temp.toLowerCase());
	}
}
